package com.huluobo.h3kotlindemo.category

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.huluobo.h3kotlindemo.R
import com.huluobo.h3kotlindemo.base.BaseMVVMFragment
import com.huluobo.h3kotlindemo.databinding.FragmentCategoryBinding

class CategoryFragment : BaseMVVMFragment<FragmentCategoryBinding>() {

    private lateinit var viewModel: CategoryViewModel

    private lateinit var parentAdapter: CategoryParentAdapter

    private lateinit var childAdapter: CategoryChildAdapter

    private val categoryParentList = mutableListOf<CategoryBean>()

    private val categoryChildList = mutableListOf<CategoryBean>()


    override fun getLayoutId(): Int = R.layout.fragment_category

    override fun initData() {
        viewModel = ViewModelProvider(requireActivity())[CategoryViewModel::class.java]

        viewModel.getCategoryList()

        viewModel.categoryListSuccess.observe(this) {
            if (it.code == 200) {
                categoryParentList.clear()
                categoryParentList.addAll(it.data)
                parentAdapter.notifyDataSetChanged()

                val data = categoryParentList[0].data
                if (data != null) {
                    categoryChildList.clear()
                    categoryChildList.addAll(data)
                    childAdapter.notifyDataSetChanged()
                }
            }
        }
    }

    override fun initView() {
        dataBinding.categoryRvParent.layoutManager = LinearLayoutManager(requireContext())
        parentAdapter = CategoryParentAdapter(categoryParentList)
        dataBinding.categoryRvParent.adapter = parentAdapter


        dataBinding.categoryRvChild.layoutManager =
            GridLayoutManager(requireContext(), 2, RecyclerView.HORIZONTAL, false)
        childAdapter = CategoryChildAdapter(categoryChildList)
        dataBinding.categoryRvChild.adapter = childAdapter
    }
}